package cn.hzw.supermarket.fragment;

import static android.app.Activity.RESULT_OK;
import static cn.hzw.supermarket.util.HttpUtil.sendHttpRequest;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.inputmethodservice.Keyboard;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.hzw.supermarket.R;
import cn.hzw.supermarket.activity.AboutActivity;
import cn.hzw.supermarket.activity.Loading3Activity;
import cn.hzw.supermarket.activity.LoginActivity;
import cn.hzw.supermarket.activity.ModifyPswActivity;
import cn.hzw.supermarket.activity.ShopMapActivity;
import cn.hzw.supermarket.activity.UpdateUsernameActivity;
import cn.hzw.supermarket.activity.UserInfoActivity;
import cn.hzw.supermarket.databinding.FragmentMeBinding;
import cn.hzw.supermarket.domain.User;
import cn.hzw.supermarket.model.ResultInfo;
import cn.hzw.supermarket.util.BitmapUtils;
import cn.hzw.supermarket.util.CameraUtils;
import cn.hzw.supermarket.util.SPUtils;
import okhttp3.OkHttpClient;


public class MeFragment extends Fragment {
    private FragmentMeBinding _binding;
    private ResultInfo resultInfo;
    private String myName;

    //权限请求
    private RxPermissions rxPermissions;
    //是否拥有权限
    private boolean hasPermissions = false;
    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;

    //存储拍完照后的图片
    private File outputImagePath;
    //启动相机标识
    public static final int TAKE_PHOTO = 1;
    //启动相册标识
    public static final int SELECT_PHOTO = 2;

    //Base64
    private String base64Pic;
    //拍照和相册获取图片的Bitmap
    private Bitmap orc_bitmap;
    //Glide请求图片选项配置
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存

    User user = new User();
    final OkHttpClient client = new OkHttpClient();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        _binding = FragmentMeBinding.inflate(inflater,container,false);
        return _binding.getRoot();

    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        //检查版本
        checkVersion();


    }


    private void initView() {
        user.setStatus("0");
        if (!readLoginStatus()) {
            _binding.myName.setOnClickListener(view -> {
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            });
            _binding.xiugai.setOnClickListener(view -> {
                Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
            });
            _binding.about.setOnClickListener(view -> {
                Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
            });
            _binding.order.setOnClickListener(view -> {
                Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
            });
            _binding.dingwei.setOnClickListener(view -> {
                Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(getContext(), ShopMapActivity.class);
//                startActivity(intent);
            });
        } else {
                _binding.myName.setText("欢迎你，"+LoginActivity.user.getUsername());
                _binding.ivHead.setImageResource(R.drawable.head);
                _binding.tvLogout.setVisibility(View.VISIBLE);
            //取出缓存

            String imageUrl = SPUtils.getString("imageUrl",null,getContext());
            if(imageUrl != null){
                Glide.with(this).load(imageUrl).apply(requestOptions).into(_binding.ivHead);
            }
                _binding.tvLogout.setOnClickListener(v ->{

                    Log.d("TAG12", "initView: "+readLoginStatus());
                    Log.d("TAG12", "initView: "+LoginActivity.user.getStatus());
                    postRequest(LoginActivity.user.getUsername());
                    _binding.tvLogout.setVisibility(View.GONE);
                    _binding.myName.setText("点击登录");
                    _binding.ivHead.setImageResource(R.drawable.ic_head_default);
                    if (_binding.myName.getText()=="点击登录") {
                        _binding.myName.setOnClickListener(view -> {
                            Intent intent = new Intent(getContext(), LoginActivity.class);
                            startActivity(intent);
                        });
                        _binding.xiugai.setOnClickListener(view -> {
                            Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
                        });
                        _binding.about.setOnClickListener(view -> {
                            Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
                        });
                        _binding.order.setOnClickListener(view -> {
                            Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
                        });
                        _binding.dingwei.setOnClickListener(view -> {
                            Toast.makeText(getContext(), "您还未登录，请先登录", Toast.LENGTH_SHORT).show();
                        });
                    }

                });
            _binding.about.setOnClickListener(view ->{
                Intent intent = new Intent(getContext(), AboutActivity.class);
                startActivity(intent);
            });
            _binding.xiugai.setOnClickListener(view -> {
                Intent intent = new Intent(getContext(), ModifyPswActivity.class);
                startActivity(intent);
            });
            _binding.dingwei.setOnClickListener(view -> {
                Intent intent = new Intent(getContext(), ShopMapActivity.class);
                startActivity(intent);
            });
            _binding.myName.setOnClickListener(view -> {
                Intent intent = new Intent(getContext(), UserInfoActivity.class);
                startActivity(intent);
//                ;
            });
            _binding.ivHead.setOnClickListener(view -> {
                changeAvatar(getView());
            });

        }
            Log.d("TAG", "initView: "+readLoginStatus());
        }
    private void postRequest(String username) {
        new Thread(() -> {
            Map<String, String> map = new HashMap<>();
            map.put("username", username);
            String response = sendHttpRequest("/user/logout", map);
            Log.d("TAG", "postRequest: "+response);
            if(response!=null&&!response.isEmpty()){
                resultInfo = JSONObject.parseObject(response, ResultInfo.class);//将JSON字符串转换成对象

                if(resultInfo.isSuccess()){
                    user=resultInfo.getUser();
                    Intent intent=new Intent(getContext(),LoginActivity.class);
                    startActivity(intent);
                }
            }
        }).start();
    }


    private boolean readLoginStatus() {

        ResultInfo resultInfo = new ResultInfo();

        Log.d("TAG", "readLoginStatus:112d "+resultInfo.getUser());
        if (LoginActivity.user==null&& user.getStatus().equals("0")){
            return false;
        }else {
            user.setStatus("1");
            return true;
        }

    }


    /**
     * 检查版本
     */
    private void checkVersion() {
        //Android6.0及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果你是在Fragment中，则把this换成getActivity()
            rxPermissions = new RxPermissions(this);
            //权限请求
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {//申请成功
                            showMsg("已获取权限");
                            hasPermissions = true;
                        } else {//申请失败
                            showMsg("权限未开启");
                            hasPermissions = false;
                        }
                    });
        } else {
            //Android6.0以下
            showMsg("无需请求动态权限");
        }
    }

    /**
     * 更换头像
     *
     * @param view
     */
    public void changeAvatar(View view) {
        bottomSheetDialog = new BottomSheetDialog(getContext());
        bottomView = getLayoutInflater().inflate(R.layout.dialog_select_photo, null);
        bottomSheetDialog.setContentView(bottomView);
        TextView tvOpenAlbum = bottomView.findViewById(R.id.tv_open_album);
        TextView tvCancel = bottomView.findViewById(R.id.tv_cancel);


        //打开相册
        tvOpenAlbum.setOnClickListener(v -> {
            openAlbum();
            showMsg("打开相册");
            bottomSheetDialog.cancel();
        });
        //取消
        tvCancel.setOnClickListener(v -> {
            bottomSheetDialog.cancel();
        });
        //底部弹窗显示
        bottomSheetDialog.show();
    }


    /**
     * 打开相册
     */
    private void openAlbum() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }
        startActivityForResult(CameraUtils.getSelectPhotoIntent(), SELECT_PHOTO);
    }

    /**
     * 返回到Activity
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            //打开相册后返回
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {

                    //判断手机系统版本号
                    //4.4及以上系统使用这个方法处理图片
                    String imagePath = CameraUtils.getImageOnKitKatPath(data, getContext());
                    //显示图片
                    displayImage(imagePath);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 通过图片路径显示图片
     */
    private void displayImage(String imagePath) {
        if (!TextUtils.isEmpty(imagePath)) {

            //放入缓存
            SPUtils.putString("imageUrl",imagePath,getContext());

            //显示图片
            Glide.with(this).load(imagePath).apply(requestOptions).into(_binding.ivHead);

            //压缩图片
            orc_bitmap = CameraUtils.compression(BitmapFactory.decodeFile(imagePath));
            //转Base64
            base64Pic = BitmapUtils.bitmapToBase64(orc_bitmap);

        } else {
            showMsg("图片获取失败");
        }
    }


    /**
     * Toast提示
     *
     * @param msg
     */
    private void showMsg(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }


}

